const ossConfig = require('./ossConfig.js'); //配置文件，配置OSS keyId和KeySecret
//Base64 编码转换算法
//hmac,sha1,crypto加密算法
const Crypto = require('./crypto.js');
const base64 = require('./base64.js');
require('./hmac.js');
require('./sha1.js');

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - type:文件类型
 *@param - successc:成功回调
 *@param - failc:失败回调
 */ 
const upload = function (filePath, dir, successc, failc) {
	if (!filePath || filePath.length > 6) {
		uni.showModal({
		  content: '文件上传错误，请重试',
		  showCancel: false,
		})
		return;
	}
	return new Promise((resolve, reject) => {
		//获取文件类型后缀 .jpg .png
		let fileType = filePath.substring(filePath.lastIndexOf('.')) || '.jpg' 
		//图片名字 可以自行定义,这里是采用当前的时间戳 + 100内的随机数来给图片命名的
		const aliyunFileKey = dir + new Date().getTime() + Math.floor(Math.random() * 100) + fileType;
		const aliyunServerURL = ossConfig.uploadImageUrl;//OSS地址，需要https
		const accessid = ossConfig.ossAccessKeyId;
		const policyBase64 = getPolicyBase64();
		const signature = getSignature(policyBase64);//获取签名
		uni.uploadFile({
			url: aliyunServerURL,//开发者服务器 url
			filePath: filePath,//要上传文件资源的路径
			name: 'file',//必须填file
			formData: {
			  'key': aliyunFileKey,
			  'policy': policyBase64,
			  'OSSAccessKeyId': accessid,
			  'signature': signature,
			  'success_action_status': '200'
			}, 
			success: (res) => {
				successc(aliyunServerURL+aliyunFileKey);
				resolve(aliyunServerURL+aliyunFileKey)
			},
			fail: (err) => {
				err.wxaddinfo = aliyunServerURL;
				failc(err);
				reject('err')
			},
		})
	})
}

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + ossConfig.timeout);
  let extime = date.toISOString();
  const policyText = {
    "expiration": extime, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
    "conditions": [
      ["content-length-range", 0, 50 * 1024 * 1024] // 设置上传文件的大小限制,50mb
    ]
  };
  
  const policyBase64 = base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64) {
  const accesskey = ossConfig.AccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {asBytes: true});
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
}

var uploadFileToOss = {
	upload: upload
}

module.exports = uploadFileToOss;